package com.zhixing.web.api.filter;

import com.zhixing.web.api.config.AllowDomainConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author dzh
 * @version 1.0.0.05020
 * <p>project: d-blog</p>
 * <p>created time: 2022/05/02 15:17</p>
 * <p>describe: 跨域拦截器</p>
 * <p>remarks: </p>
 **/
@Component
public class CorsFilter implements Filter {

    private AllowDomainConfig allowDomainConfig;

    @Autowired
    public CorsFilter(AllowDomainConfig allowDomainConfig) {
        this.allowDomainConfig = allowDomainConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;

        String[] allowDomain = allowDomainConfig.getDomain();

        //noinspection unchecked
        Set allowedOrigins = new HashSet(Arrays.asList(allowDomain));

        String originHeader = ((HttpServletRequest) req).getHeader("Origin");

        if (allowedOrigins.contains(originHeader)) {

            response.setHeader("Access-Control-Allow-Origin", originHeader);
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true");
        }

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}
